import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter_base_app/generated/assets.dart';
import 'package:flutter_base_app/utils/vk_image_utils.dart';
import 'package:flutter_base_app/widgets/dialog/base/loading_dialog.dart';
import 'package:flutter_base_app/widgets/image/svg_widget.dart';

import '../../config/app_colors.dart';

///9宫格选择的图片
class ImagePickerGridWidget extends StatefulWidget {
  final int maxCount;
  final ValueChanged<List<File>> onChanged;

  const ImagePickerGridWidget({super.key, this.maxCount = 9, required this.onChanged});

  @override
  State<ImagePickerGridWidget> createState() => _ImagePickerGridWidgetState();
}

class _ImagePickerGridWidgetState extends State<ImagePickerGridWidget> {
  final List<File> _selectedImages = []; // 已选中的图片
  bool get isFull => _selectedImages.length >= widget.maxCount;

  //选择图片
  Future<void> _pickImages() async {
    if (isFull) {
      return;
    }
    // 检查权限
    // final status = await Permission.photos.request();
    // LogUtils.e("_pickImages   $status");
    // if (!status.isGranted) return;

    // 选择图片
    final List<XFile> images = await ImagePicker().pickMultiImage(limit: (widget.maxCount - _selectedImages.length).clamp(2, widget.maxCount));
    //最大数量限制
    if (images.length + _selectedImages.length > widget.maxCount) {
      //去除后面得
      images.removeRange(widget.maxCount - _selectedImages.length, images.length);
    }
    final loadTag = showLoadingDialog();
    for (var it in images) {
      try {
        final File file = await VkImageUtils.compressImage(File(it.path));
        _selectedImages.add(file);
      } catch (e) {
        _selectedImages.add(File(it.path));
      }
    }
    loadTag.dismiss();
    widget.onChanged(_selectedImages);
    setState(() {});
  }

  // 删除图片
  void _removeImage(File image) {
    setState(() {
      _selectedImages.remove(image);
      widget.onChanged(_selectedImages);
    });
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      physics: const NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
        childAspectRatio: 1,
      ),
      itemCount: isFull ? _selectedImages.length : _selectedImages.length + 1,
      // +1 为添加按钮
      itemBuilder: (context, index) {
        if (index == _selectedImages.length) {
          return _buildAddButton(); //最后Item是“添加”按钮
        } else {
          return _buildImageItem(_selectedImages[index]);
        }
      },
    );
  }

  // 添加按钮
  Widget _buildAddButton() {
    return GestureDetector(
      onTap: _pickImages,
      child: Container(
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(4), color: ColorsApp.gray_e5),
        child: Icon(Icons.add, size: 40),
      ),
    );
  }

  // 图片Item
  Widget _buildImageItem(File image) {
    return Container(
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(4), color: ColorsApp.gray_e5),
      clipBehavior: Clip.hardEdge,
      child: Stack(
        children: [
          Positioned.fill(child: Image.file(image, fit: BoxFit.cover)),
          Positioned(
            right: 3,
            top: 3,
            child: GestureDetector(
              onTap: () => _removeImage(image),
              // child: SvgWidget(Assets.svgIcDeleteCircleMain),
            ),
          ),
        ],
      ),
    );
  }
}
